<?php
/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */
namespace app\api\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\admin\model\Platform;
use app\admin\model\SmsMessage;
use app\admin\model\SystemConfig;
use app\api\controller\system\Config;
use app\common\controller\AdminController;
use think\captcha\facade\Captcha;
use think\facade\Env;
use Firebase\JWT\JWT;
use think\facade\Db;
use think\Model;
use app\admin\model\SystemLoginRecord;
use app\admin\model\SystemUser;
use think\facade\Cache;

/**
 * Class Login
 *
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 用户登录
     *
     * @return string
     * @throws \Exception
     */
    public function login()
    {
        try {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $rule = [
                    'username|用户名' => 'require',
                    'password|密码' => 'require'
                ];
                $this->validate($post, $rule);
                $record = [
                    'username' => $post['username'],
                    'os' => get_os(),
                    'device' => get_os(),
                    'browser' => get_broswer(),
                    'ip' => $this->request->ip(),
                    'tenant_id' => 0,
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time())
                ];
                $loginRecord = new SystemLoginRecord();
                $admin = Db::name("system_user")->where("username", $post['username'])->find();
                if (empty($admin)) {
                    $record['login_type'] = 1;
                    $record['comments'] = '用户不存在';
                    $loginRecord->save($record);
                    $loginRecord->save($record);
                    return msg([], 1002, "用户不存在!");
                }
                $record['tenant_id'] = $admin['tenant_id'];
                if ($admin['status'] == 1) {
                    $record['login_type'] = 1;
                    $record['comments'] = '账号冻结';
                    $loginRecord->save($record);
                    return msg([], 1004, "账号冻结!");
                }
                if ($admin['password'] != md5($post['password'])) {
                    $record['login_type'] = 1;
                    $record['comments'] = '密码错误';
                    $loginRecord->save($record);
                    return msg([], 1004, "密码错误!");
                }
                if ($admin['tenant_id'] ==2){
                    $platformModel  = new Platform();
                    $platformInfo = $platformModel->where(['id' => $admin['platform_id']])->find();

                    if ( $platformInfo['expiration_time'] < time()){
                        $record['login_type'] = 1;

                        $record['comments'] = '平台已过期';

                        $loginRecord->save($record);

                        return msg([], 1004, "平台已过期!");
                    }

                }

                unset($admin['password']);
                $admin['expire_time'] = time() + 7200;
                $user_id = $admin['user_id'];
                session('admin', $admin);
                // 权限
                $token = signToken([
                    "uid" => $user_id,
                    "tenant_id" => $admin['tenant_id']
                ]);
                $menu = Db::name("system_role_menu")->alias("a")
                    ->leftJoin("system_menu b", "a.menu_id=b.menu_id")
                    ->field("b.*,
            b.menu_id menuId,
            b.parent_id parentId,
            b.menu_type menuType,
            b.sort_number sortNumber,
            b.tenant_id tenantId,
            b.update_time updateTime,
            b.create_time createTime,
            a.tenant_id tenantId
            ")
                    ->where("a.role_id", "in", function ($query) use($user_id) {
                        if ($user_id == 1){
                            $query->name("system_user_role")
                               // ->where("user_id", $user_id)
                                ->field("role_id");
                        }else{
                            $query->name("system_user_role")
                                ->where("user_id", $user_id)
                                ->field("role_id");
                        }

                })
                    ->select();
                //

                if ($admin['platform_id'] > 0){
                    $roles = Db::name("system_role")->alias("a")
                        ->field("a.*,a.role_id roleId,a.role_name roleName,a.role_code roleCode,a.tenant_id tenantId,a.create_time createTime,a.update_time updateTime")
                        ->where("a.role_id", 2)
                        ->select();
                }else{
                    $roles = Db::name("system_role")->alias("a")
                        ->field("a.*,a.role_id roleId,a.role_name roleName,a.role_code roleCode,a.tenant_id tenantId,a.create_time createTime,a.update_time updateTime")
                        ->where("a.role_id", 1)
                        ->select();
                }

                
                $admin['authorities'] = $menu;
                $admin['roles'] = $roles;
                $admin['accountNonExpired'] = true;
                $admin['accountNonLocked'] = true;
                
                $record['login_type'] = 0;
                $record['comments'] = '登录成功';
                $loginRecord->save($record);
                
                return msg([
                    "access_token" => $token,
                    "user" => $admin,
                  'platform_id'  => $admin['platform_id']
                ], 0, "请求成功");
            }
            
            return msg([], 1001, "请求方式错误!");
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage(), $e->getTrace());
            exit();
        }
    }

    /**
     * 用户信息
     *
     * @return mixed
     */
    public function user()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        
        $user = Db::name("system_user")->where("user_id", $user_id)->find();
        
        return msg($user, 0, "");
    }

    /**
     * 用户退出
     *
     * @return mixed
     */
    public function out()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        $user = Db::name("system_user")->where("user_id", $user_id)->find();
        
        $record = [
            'username' => $user['username'],
            'os' => get_os(),
            'device' => get_os(),
            'browser' => get_broswer(),
            'ip' => $request->ip(),
            'login_type' => 2,
            'tenant_id' => 1,
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time())
        ];
        
        $loginRecord = new SystemLoginRecord();
        $loginRecord->save($record);
        
        session('admin', null);
        $this->success('退出登录成功');
    }

    /**
     * 验证码
     *
     * @return \think\Response
     */
    public function captcha()
    {
        $c = Captcha::createApi();
        
        return msg($c, 0, "操作成功");
    }

    /**

     * 用户注册

     *

     * @return mixed

     */

    public function register()
    {
        try {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $rule = [
                    'phone|用户名' => 'require',
                    'password|密码' => 'require',
                    'code|验证码' => 'require'
                ];
                $this->validate($post, $rule);
                $phone = $post['phone'];
                $code = $post['code'];
                $password = $post['password'];
                $smsMessageModel = new SmsMessage();
                $smsMessageInfo = $smsMessageModel->where(['telphone' =>$phone, 'code' => $code])->order('create_time', 'desc')->find();
                if (empty($smsMessageInfo)) {
                    return result(-1, '无效验证码');
                }
                if ( time() > $smsMessageInfo['effective_time']   ) {
                    return result(-1, '验证码过期');
                }
                $admin = Db::name("system_user")->where("username", $phone)->find();
                if (! empty($admin)) {
                    return msg([], 1002, "账号已存在!");
                }
                $platformModel = new Platform();
                $platformModel->save([
                    'tenant_id' => 2,
                    'telphone' => $phone,
                    'name' => $post['username'],
                    'create_time' => date('Y-m-d H:i:s', time())
                ]);

                $systemUser = new SystemUser();
                $systemUser->save([
                    'tenant_id' => 2,
                    'username' => $phone,
                    'password' => md5($password),
                    'nickname' => $phone,
                    "phone" => $phone,
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'platform_id' => $platformModel->id,
                ]);

                return msg([], 0, "注册成功!");
                    //修改验证码状态
            }
            return msg([], 1001, "请求方式错误!");

        } catch (\Exception $e) {

            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage(), $e->getTrace());

            exit();

        }

    }

    public function sendCode()

    {
        $request = $this->request;
        $param = $request->param();
        $chars = '0123456789';
        $str = '';
        for ($i = 0; $i < 4; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $message = sysconfig('message');
        $config = new Config(['accessKeyId' => $message['alimessage_access_key_id'], 'accessKeySecret' => $message['alimessage_access_key_secret']]);
        $config->endpoint ="dysmsapi.aliyuncs.com";
        $client = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $param['telphone'],
            "signName" => $message['alimessage_template_name'],    //    签名
            "templateCode" => $message['alimessage_tid'],    //    模板
            "templateParam" => json_encode(['code' => $str])
        ]);
        $runtime = new RuntimeOptions([]);
        $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($res->body->code == 'OK') {
            $smsMessageModel = new SmsMessage();
            $smsMessageModel->insert([
                'telphone' => $param['telphone'],
                'create_time' => time(),
                'code' => $str,
                'effective_time' => time() + 300
            ]);
            return result(0, '发送成功');
        } else {
            return result(-1,'发送失败');
        }


    }
}
